package com.miplus.ccrm.sms;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.miplus.ccrm.common.JPubUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataUnit;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Service
public class JSmsService {
    @Value("${ccrm.sms.url}")
    private String smsUrl;

    //系统Id或平台ID
    @Value("${ccrm.sms.source:}")
    private String smsSource;

    //产品号
    @Value("${ccrm.sms.accesskey:}")
    private String smsAccessKey;

    @Value("${ccrm.sms.channel:}")
    private String smsChannel;

    //产品号
    @Value("${ccrm.sms.prod:}")
    private String smsProdId;

    //业务归属
    @Value("${ccrm.sms.busitype:}")
    private String smsbusiType;

    public JSmsService()
    {

    }

    //发送短信
    //srvIpaddr=提交者IP地址
    //channel=短信通道
    //typecode=类型编码
    //phone=客户号码
    //content=短信内容或参数
    public SmsR SendSms(String srvIpaddr,String tempid,String typecode,String phone,String content)
    {
        log.info("SendSms:Ipaddr={},tempid={},typecode={}",srvIpaddr,tempid,typecode);

        String mac= md5Encryption(smsSource+smsAccessKey);

        JSONObject bodyJson=new JSONObject();
        bodyJson.put("platformId",smsSource);
        bodyJson.put("mac",mac);
        bodyJson.put("templateId",tempid);
        bodyJson.put("channelId",smsChannel);
        bodyJson.put("code",typecode);
        bodyJson.put("mobile",phone);
        bodyJson.put("param",content);

        String requestBody=bodyJson.toJSONString();

        log.info("SendSms:{}",requestBody);

        try {
            String sendUrl=smsUrl;
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sendUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                JsonNode respBody=jsonResponse.getBody();
                log.info("SendSms.Response:{}", respBody);
                String code=respBody.getObject().getString("code");
                String seqNo="0";
                if(JPubUtils.IsEqual(code,"0000")){
                    try {
                        seqNo = respBody.getObject().getJSONObject("data").getString("batchNo");
                    }
                    catch (Exception err){
                        log.warn("SendSms.GetSeqNoFail:{}",err.getMessage());
                    }
                    return SmsR.Success(seqNo);
                }
                else{
                    String message=respBody.getObject().getString("message");
                    return SmsR.Error(JPubUtils.StringToInt(code),message);
                }
            } else {
                log.warn("SendSms.Fail:Status={},Cause={}", status, jsonResponse.getStatusText());
                return SmsR.Error(status,jsonResponse.getStatusText());
            }
        }
        catch (Exception e){
            log.warn("SendSms.Err:{}", e.getMessage());

            return SmsR.Error(-1,e.getMessage());
        }
    }

    //发送模板短信
    public SmsR SendTempSms(String srvIpaddr,String sysSeqNo,String phone,String tmplId,String tmplParm)
    {
        String seqNo=smsChannel+sysSeqNo;

        log.info("SendTempSms:Ipaddr={},seqNo={},tmplId={},tmplParm={}..",srvIpaddr,seqNo,tmplId,tmplParm);

        JSONObject objJson=new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        JSONObject headJson=new JSONObject();
        headJson.put("chlType",smsChannel);
        headJson.put("svcCd","MSGO0007");
        headJson.put("svcScn","MSGO");
        headJson.put("tranDt",sdf.format(new Date()));
        sdf = new SimpleDateFormat("HHmmssSSS");
        headJson.put("tranTm",sdf.format(sdf));
        headJson.put("glblSeqNo",seqNo);
        headJson.put("cnsmSysSeqNo",seqNo);
        headJson.put("cnsmSysId",smsSource);
        headJson.put("cnsmSysSvrId",srvIpaddr);

        objJson.put("sysHead",headJson);

        JSONObject bodyJson=new JSONObject();
        bodyJson.put("tmplId",tmplId);
        bodyJson.put("tmplParm",tmplParm);
        bodyJson.put("mobiles",phone);
        bodyJson.put("clientId","");

        objJson.put("body",bodyJson);

        String requestBody=objJson.toJSONString();

        log.info("SendTempSms:{}",requestBody);

        try {
            String sendUrl=smsUrl+"/MSGO/MSGO0007";
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sendUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                log.info("SendTempSms.Response:{}", jsonResponse.getBody());
                return SmsR.Success(seqNo);
            } else {
                log.warn("SendTempSms.Fail:Status={},Cause={}", status, jsonResponse.getStatusText());
                return SmsR.Error(status,jsonResponse.getStatusText());
            }
        }
        catch (Exception e){
            log.warn("SendTempSms.Err:{}", e.getMessage());

            return SmsR.Error(-1,e.getMessage());
        }
    }

    public String md5Encryption(String s)
    {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hashBytes = digest.digest(s.getBytes());
            StringBuilder hexBuilder = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3);
                hexBuilder.append(hex);
            }
            return hexBuilder.toString();
        }
        catch (NoSuchAlgorithmException e){
            log.warn("md5Encryption.Err:{}",e.getMessage());
        }
        return "";
    }
}
